substring() method
This method will allow you to provide you with the part of the specified string. For this, the start and the end index have to be delivered by specifying the substring. But the start index is inclusive, and the end index is exclusive of the part. Thus the index starts from zero.
Method implementation-
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
Syntax-
public String substring(int startIndex)
and
public String substring(int startIndex, int endIndex)
This method will throw StringIndexOutOfBoundException if you are using the start index value as negative or if the end index value is less than the start index.
Example-
public class Simple{
public static void main(String[] args) {
String s1="welcome to Java and welcome to tutorial";
System.out.println(s1.substring(4,9));
}
}
Output-
Example-
public class Simple{
public static void main(String[] args) {
String s1="welcome to Java and welcome to tutorial";
System.out.println(s1.substring(0));
}
}
Output-